package flower.com.fenzu35011111;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

import java.util.ArrayList;
import java.util.List;

import flower.com.fenzu35011111.bean.Groups;
import flower.com.fenzu35011111.db.Z_Groups_Dao;
import flower.com.fenzu35011111.fragment.Fragment;

public class MainActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager viewPage;
    Z_Groups_Dao z_groups_dao = new Z_Groups_Dao(this);
    private List<String> titles;


    private android.support.v4.app.Fragment[] f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPage = (ViewPager) findViewById(R.id.viewPage);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        titles = new ArrayList<>();


    }

    Myadapter adapter;

    @Override

    protected void onResume() {
        titles.clear();
        super.onResume();
        List<Groups> queryall = z_groups_dao.queryall();
        for (int i = 0; i < queryall.size(); i++) {

            titles.add(queryall.get(i).getName());
        }
        tabLayout.setupWithViewPager(viewPage);
        adapter = new Myadapter(getSupportFragmentManager());
        //联动
        viewPage.setAdapter(adapter);
    }

    //适配器
    class Myadapter extends FragmentPagerAdapter {

        public Myadapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return getfragment(position);
        }

        @Override
        public int getCount() {
            return titles.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);
        }
    }

    //动态创建Fragment的方法
    public android.support.v4.app.Fragment getfragment(int position) {
        List<Groups> queryall = z_groups_dao.queryall();
        f = new android.support.v4.app.Fragment[queryall.size()];
        android.support.v4.app.Fragment fg = f[position];
        if (fg == null) {
            fg = Fragment.getiniturl(position + "");
            f[position] = fg;
        }
        return fg;
    }
}
